package com.photoeditor.demo.util;

import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;

import com.common.base.ComponentContext;
import com.photoeditor.demo.model.filter.FilterPluginsHelper;

import java.io.File;
import java.util.LinkedHashMap;

public class ResourceManager {

    private static ResourceManager mInstance;

    private LinkedHashMap<String, Resources> mResources;

    private static final int CACHE_SIZE = 2;

    private ResourceManager(){
        mResources = new LinkedHashMap<String, Resources>(CACHE_SIZE, 0.5f, true){

            private static final long serialVersionUID = 75867L;

            @Override
            protected boolean removeEldestEntry(Entry<String, Resources> eldest) {
                if (size() > CACHE_SIZE) {
                    return true;
                }
                return super.removeEldestEntry(eldest);
            }
        };
    }

    public synchronized static ResourceManager getInstance(){
        if(mInstance == null){
            mInstance = new ResourceManager();
        }
        return mInstance;
    }

    public Resources getResources(String pkgName){
        if(!TextUtils.isEmpty(pkgName)) {
            if (ComponentContext.getPackageName().equals(pkgName)){
                return ComponentContext.getContext().getResources();
            } else {
                Resources res = mResources.get(pkgName);
                if (res == null) {
                    Context context = ComponentContext.getContext();
                    Context mApkContext = null;
                    try {
                        mApkContext = context.createPackageContext(pkgName, Context.CONTEXT_IGNORE_SECURITY);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    if (mApkContext != null) {
                        res = mApkContext.getResources();
                        mResources.put(pkgName, res);
                        return res;
                    }
                }
                return res;
            }
        }
        return null;
    }

    /**
     * 获取未安装Apk的信息
     * @param path
     * @return
     */
    public Resources getUnInstallApkResource(String path, String packageName){
        File f = new File(path);
        if(f.exists()) {
            Resources resources = FilterPluginsHelper.getUninstallAPKInfo(ComponentContext.getContext(), path);
            return resources;
        }
        return null;
    }
}
